/*
 * Copyright 2012-2013 Finbudget.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package finbudgettable.client.ui.grid.cell.link;

import com.google.gwt.cell.client.Cell;
import finbudget.client.ui.table.LinkField;
import finbudget.client.ui.table.Record;
import finbudget.shared.process.events.StringPair;
import finbudgettable.client.ui.grid.CellGrid;
import finbudgettable.client.ui.grid.column.GridColumn;

public class LinkColumn extends GridColumn<StringPair> {

	private final UrlBuilder linkBuilder;
	/**
	 * Optional name of the Record's field that stores
	 * caption for the cell.
	 */
	private final String nameFieldId;

	public LinkColumn(Builder builder) {
		super(builder);
		this.linkBuilder = builder.linkBuilder;
		this.nameFieldId = builder.linkField.getFieldName();
	}

	@Override
	protected boolean isValueChanged(Record record, StringPair value) {
//		return CommonComparator.isNotEqual(getValue(record), value);
		// The cell is static
		return false;
	}

	@Override
	protected String getCellStyleNames() {
		return LinkCell.RESOURCES.style().bLinkCell();
	}

	@Override
	public StringPair getValue(Record record) {
		return new StringPair(record.getValueString(nameFieldId), linkBuilder.build(record));
	}

	public static class Builder extends GridColumn.Builder<LinkCell, StringPair> {

		private final LinkField linkField;
		private final UrlBuilder linkBuilder;

		Builder(CellGrid grid, LinkField linkField, boolean hasTotals) {
			super(grid, linkField.getLinkTemplate(), hasTotals);
			this.linkField = linkField;
			setCaption(linkField.captionGrid);
			linkBuilder = new UrlBuilder(linkField.getLinkTemplate(), linkField.getParameters(), linkField.getPairParameters(), linkField.isAllLinkFieldsRequired());
		}

		@Override
		protected LinkCell createCell() {
			return new LinkCell(linkField.captionGrid);
		}

		@Override
		protected GridColumn<StringPair> createColumn(Cell<StringPair> cell) {
			return new LinkColumn(this);
		}
	}

	public static Builder builder(CellGrid grid, LinkField linkField, boolean hasTotals) {
		return new Builder(grid, linkField, hasTotals);
	}
}
